package com.mp.approvalreq.servlet.other.module;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.common.ResultBean;
import com.mp.approvalreq.entity.*;
import com.mp.approvalreq.entity.common.Constants;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.service.RequestServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * 通用的获取审批列表
 * 参数:{ "companyId":1829, "requestDkeyList":"[{12265,24134,61853}] }"
 *
 * @author xq
 */
@WebServlet("/getRequestList")
public class GetRequestList extends AbstractServlet {

	private static final Logger logger = LoggerFactory.getLogger(GetRequestList.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);

			JSONObject jsObj = checkAndGetInput(req);

			List<Integer> requestIds = getRequestIds(jsObj);
			RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);
			Query query = new Query(user);
			query.setRequestIds(Utils.list2string(requestIds));
			List<Request> list = requestServicePrx.getRequestListByIds(query);

			returnResp(resp, list);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}

	private void returnResp(HttpServletResponse resp, List<Request> list) throws Throwable {
		List<ReqListParam> listParams = changeRequestList(list);
		ResultBean<List<ReqListParam>> resultBean = new ResultBean<>("data", listParams);

		logger.info(JSON.toJSONString(resultBean));

		printJson(resp, JSON.toJSONString(resultBean));
	}

	private JSONObject checkAndGetInput(HttpServletRequest req) throws Exception {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);

		JSONObject jo;
		try {
			jo = JSON.parseObject(reqBody);
		} catch (Exception e) {
			throw new RpcServerLogicalException(1, "参数错误");
		}

		JSONArray arr = jo.getJSONArray("requestIds");
		if (arr == null || arr.isEmpty()) {
			logger.info("req.getCookies():{}", JSONObject.toJSONString(req.getCookies()));
			throw new RpcServerLogicalException(1, "审批集合为空");
		}

		return jo;
	}


	private List<Integer> getRequestIds(JSONObject jsObj) {
		String jsonStr = jsObj.getJSONArray("requestIds").toJSONString();
		return JSONArray.parseArray(jsonStr, Integer.class);
	}

	private List<ReqListParam> changeRequestList(List<Request> reqList) {
		List<ReqListParam> reqListParams = new LinkedList<>();
		for (Request req : reqList) {
			reqListParams.add(changeRequest(req));
		}
		return reqListParams;
	}

	private ReqListParam changeRequest(Request req) {
		ReqListParam listParam = new ReqListParam();
		listParam.setRequestDkey(req.getRequestDkey());
		listParam.setDefaultType(req.getDefaultType());
		listParam.setApplicant(req.getApplicant());
		listParam.setApplicantName(req.getApplicantName());
		listParam.setFinished(req.getFinished());
		listParam.setRequestTime(req.getRequestTime());
		listParam.setRequestName(req.getTemplateName());
		listParam.setStartTime(req.getStartTime());
		listParam.setNaturalContentTimeLast(req.getNaturalContentTimeLast());
		listParam.setTemplateColor(req.getTemplateColor());
		listParam.setTemplateId(req.getTemplateId());
		int requestAncestorId = Utils.isNull(req.getRequestAncestorId()) ? 0 : req.getRequestAncestorId();
		listParam.setRequestAncestorId(requestAncestorId);
		listParam.setVersion(req.getVersion());
		showRequestContentByTemplateType(req, listParam);
		return listParam;
	}

	private void showRequestContentByTemplateType(Request request, ReqListParam reqListParam) {
		List<TemplateComponent> components = request.getComponentsContent();
		for (TemplateComponent com : components) {
			if (request.getDefaultType() == Template.LEAVE) {
				// 请假开始时间
				if (com.getNum() == 1 && com.getType() == ContentType.TIME) {
					reqListParam.setStartTime(com.getValue());
				}
				// 请假原因
				if (com.getNum() == 4 && com.getType() == ContentType.TEXT) {
					reqListParam.setLeaveReson(com.getValue());
				}
			} else if (request.getDefaultType() == Template.COMPENSATORY_LEAVE) {
				// 请假开始时间
				if (com.getNum() == 1 && com.getType() == ContentType.TIME_RANGE) {
					reqListParam.setStartTime(com.getValue());
				}

				if (com.getNum() == 4 && com.getType() == ContentType.TEXT) {
					// 请假原因
					reqListParam.setLeaveReson(com.getValue());
				}
			}

		}
	}
}